package com.haoshui.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.haoshui.domain.entity.UserRole;
import com.haoshui.mapper.UserRoleMapper;
import com.haoshui.service.UserRoleService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户和角色关联表(UserRole)表服务实现类
 *
 * @author makejava
 * @since 2022-09-30 20:24:45
 */
@Service("userRoleService")
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements UserRoleService {

    @Override
    public boolean addUserRole(Long id, List<Long> roleIds) {
        //变换格式
        List<UserRole> userRoles = roleIds.stream()
                .map(roleId -> new UserRole(id, roleId))
                .collect(Collectors.toList());

        //添加
        boolean b = saveBatch(userRoles);

        return b;
    }

    @Override
    public List<Long> getRoleIdsByUserId(Long id) {
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRole::getUserId, id);

        List<UserRole> list = list(queryWrapper);

        List<Long> collect = list.stream().map(o -> o.getRoleId()).collect(Collectors.toList());

        return collect;
    }

    @Override
    public boolean updateUserRole(Long id, List<Long> roleIds) {
        //转化成UserRoles
        List<UserRole> collect = roleIds.stream()
                .map(o -> new UserRole(id, o))
                .collect(Collectors.toList());

        //更新
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRole::getUserId, id);
        if(list(queryWrapper).size()>0){
            remove(queryWrapper);
        }

        if(collect.size()>0){
            boolean b = saveBatch(collect);
            return b;
        }else{
            return true;
        }
    }

}
